package com.generic.util;

import java.io.File;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class FileUtil {
	private static final Log log = LogFactory.getLog(FileUtil.class);
	
	public static void delete(String fileName) {
		// A File object to represent the filename
		File f = new File(fileName);

		// Make sure the file or directory exists and isn't write protected
		if (!f.exists()) {
			log.error("Delete: no such file or directory: " + fileName);
			throw new IllegalArgumentException("Delete: no such file or directory: " + fileName);
		}
		if (!f.canWrite()) {
			log.error("Delete: write protected: " + fileName);
			throw new IllegalArgumentException("Delete: write protected: " + fileName);
		}
		// If it is a directory, make sure it is empty
		if (f.isDirectory()) {
			String[] files = f.list();
			if (files.length > 0) {
				log.error("Delete: directory not empty: " + fileName);
				throw new IllegalArgumentException("Delete: directory not empty: " + fileName);
			}
		}

		// Attempt to delete it
		boolean success = f.delete();

		if (!success) {
			log.error("Delete: deletion failed");
			throw new IllegalArgumentException("Delete: deletion failed");
		}
	}
	
	public static boolean deleteDirectory(String fileName) {
		File f = new File(fileName);		
		return deleteDirectory(f);
	}
	
	public static boolean deleteDirectory(File f) {
		if (f.exists()) {
			File[] files = f.listFiles();
			for (int i = 0; i < files.length; i++) {
				if (files[i].isDirectory()) {
					deleteDirectory(files[i]);
				} else {
					files[i].delete();
				}
			}
		}
		return (f.delete());
	}
}
